<template>
  <view class="content">
    <view class="log_head">
      <button type="primary" @click="getlogin" class="log_btn">微信登录</button>
    </view>
  </view>
</template>

<script>
// 引入请求模块
import { postRequest } from "@/api/api.js";
// 引入url
import { postUserInfo } from "@/api/request.js";
export default {
  name: "login",
  mounted() {},
  data() {
    return {
      globalData: {
        appid: "wxe1e5643a823e813c",
        secret: "517bd39b176223f906d11ed364ad7277",
      },
      userInfo: {},
      is_post: false,
      hasUserInfo: false,
    };
  },
  methods: {
    // 获取用户的头像和昵称信息
    getUserProfile(e) {
      const that = this;
      wx.getUserProfile({
        desc: "用于登录该小程序，记录个人信息", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(res);
          that.userInfo = res.userInfo;
          uni.setStorage({
            key: "userInfo",
            data: res.userInfo,
            success: function () {
              console.log("set userInfo success");
            },
          });
        },
      });
    },
    // 微信授权登录
    async getlogin() {
      var that = this;
      wx.showLoading({
        title: "加载中",
      });
      //登录凭证校验。通过 wx.login() 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。
      await wx.getUserProfile({
        desc: "用于登录该小程序，记录个人信息", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(res);
          that.userInfo = res.userInfo;
          uni.setStorage({
            key: "userInfo",
            data: res.userInfo,
            success: function () {
              console.log("set userInfo success");
            },
          });
          uni.reLaunch({
            url: `/pages/mine/mine`,
            fail: (err) => {
              console.log(err);
            },
            success() {
              console.log("switchTab success");
              // beforePage.onLoad();
            },
          });
          wx.login({
            success: function (res) {
              console.log(res);
              if (res.code) {
                console.log("res.code:" + res.code);
                var d = that.globalData; //这里存储了appid、secret、token串
                var l =
                  "https://api.weixin.qq.com/sns/jscode2session?appid=" +
                  d.appid +
                  "&secret=" +
                  d.secret +
                  "&js_code=" +
                  res.code +
                  "&grant_type=authorization_code";
                wx.request({
                  url: l,
                  data: {},
                  method: "GET",
                  success: function (res) {
                    console.log(res);
                    // 储存token
                    if (!that.is_post) {
                      postRequest(postUserInfo, res.data)
                        .then((result) => {
                          console.log(result);
                          let token = result[1].data.token;
                          uni.setStorage({
                            key: "token",
                            data: token,
                            success: function () {
                              console.log("set token success");
                            },
                          });
                          // let pages = getCurrentPages(); // 当前页面
                          // let beforePage = pages[pages.length - 2]; // 上一页

                          // uni.reLaunch({
                          //   url: `/pages/mine/mine`,
                          //   fail: (err) => {
                          //     console.log(err);
                          //   },
                          //   success() {
                          //     console.log("switchTab success");
                          //     beforePage.onLoad();
                          //   },
                          // });
                        })
                        .catch((err) => {
                          console.log(err);
                        });
                      that.is_post = true;
                    }
                  },
                  fail: (err) => {
                    console.log(err);
                  },
                });
              } else {
                console.log("获取用户登录态失败！" + res.errMsg);
              }
            },
            fail: (err) => {
              console.log(err);
            },
          });
        },
      });
      wx.hideLoading();
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  .log_head {
    width: 100%;
    height: 50vh;
    position: relative;
    .log_btn {
      width: 60%;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      top: 20%;
      text-align: center;
    }
  }
}
</style>